window.TextDiffRenderer = class TextDiffRenderer {
    static getHTML() {
        return `
            <div class="tool-content">
                <h2 class="text-3xl font-bold text-gray-800 mb-6 flex items-center">
                    <i data-feather="git-branch" class="mr-3"></i>
                    文本差异对比工具
                </h2>
                
                <div class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-6">
                    <p class="text-blue-800">
                        <i data-feather="info" class="inline w-4 h-4 mr-1"></i>
                        高效对比两段文本的差异，支持代码审查、文档对比、版本比较等场景
                    </p>
                </div>

                <!-- 输入区域 -->
                <div class="space-y-6 mb-6">
                    <!-- 原始文本 -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-xl font-semibold text-gray-800 flex items-center">
                                <i data-feather="file-text" class="w-6 h-6 mr-3 text-red-500"></i>
                                原始文本
                            </h3>
                            <div class="flex space-x-3">
                                <label class="bg-blue-600 hover:bg-blue-700 text-white text-sm px-4 py-2 rounded-lg cursor-pointer flex items-center transition duration-200">
                                    <i data-feather="upload" class="w-4 h-4 mr-2"></i>
                                    上传文件
                                    <input type="file" id="upload-original" class="hidden" accept=".txt,.js,.css,.html,.json,.xml,.md,.py,.java,.cpp,.c,.h,.php,.rb,.go,.rs,.ts,.jsx,.vue,.svelte">
                                </label>
                                <button id="clear-original" class="text-red-600 hover:text-red-800 text-sm px-4 py-2 rounded-lg border border-red-300 hover:bg-red-50 flex items-center transition duration-200">
                                    <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                                    清空
                                </button>
                            </div>
                        </div>
                        <textarea 
                            id="original-text" 
                            placeholder="粘贴或输入原始文本内容..."
                            class="w-full h-48 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical font-mono text-sm leading-relaxed"
                        ></textarea>
                        <div class="text-sm text-gray-600 mt-3 flex justify-between items-center">
                            <span id="original-stats">字符: 0, 行数: 0</span>
                            <span id="original-filename" class="text-blue-600 font-medium"></span>
                        </div>
                    </div>

                    <!-- 修改后文本 -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-xl font-semibold text-gray-800 flex items-center">
                                <i data-feather="file-text" class="w-6 h-6 mr-3 text-green-500"></i>
                                修改后文本
                            </h3>
                            <div class="flex space-x-3">
                                <label class="bg-blue-600 hover:bg-blue-700 text-white text-sm px-4 py-2 rounded-lg cursor-pointer flex items-center transition duration-200">
                                    <i data-feather="upload" class="w-4 h-4 mr-2"></i>
                                    上传文件
                                    <input type="file" id="upload-modified" class="hidden" accept=".txt,.js,.css,.html,.json,.xml,.md,.py,.java,.cpp,.c,.h,.php,.rb,.go,.rs,.ts,.jsx,.vue,.svelte">
                                </label>
                                <button id="clear-modified" class="text-red-600 hover:text-red-800 text-sm px-4 py-2 rounded-lg border border-red-300 hover:bg-red-50 flex items-center transition duration-200">
                                    <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                                    清空
                                </button>
                            </div>
                        </div>
                        <textarea 
                            id="modified-text" 
                            placeholder="粘贴或输入修改后的文本内容..."
                            class="w-full h-48 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical font-mono text-sm leading-relaxed"
                        ></textarea>
                        <div class="text-sm text-gray-600 mt-3 flex justify-between items-center">
                            <span id="modified-stats">字符: 0, 行数: 0</span>
                            <span id="modified-filename" class="text-blue-600 font-medium"></span>
                        </div>
                    </div>
                </div>

                <!-- 对比选项 -->
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i data-feather="settings" class="w-5 h-5 mr-2"></i>
                        对比选项
                    </h3>
                    
                    <div class="grid md:grid-cols-3 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">对比粒度</label>
                            <select id="split-by" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="lines">按行对比（推荐）</option>
                                <option value="words">按单词对比</option>
                                <option value="chars">按字符对比</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">上下文行数</label>
                            <input type="number" id="context-lines" value="3" min="0" max="10" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">显示选项</label>
                            <div class="space-y-2">
                                <label class="flex items-center">
                                    <input type="checkbox" id="show-line-numbers" checked class="mr-2 rounded">
                                    <span class="text-sm">显示行号</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" id="ignore-whitespace" class="mr-2 rounded">
                                    <span class="text-sm">忽略空白字符</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" id="ignore-case" class="mr-2 rounded">
                                    <span class="text-sm">忽略大小写</span>
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-center mt-6">
                        <button id="compare-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-lg transition duration-200 flex items-center">
                            <i data-feather="git-compare" class="w-5 h-5 mr-2"></i>
                            开始对比
                        </button>
                    </div>
                </div>

                <!-- 对比结果 -->
                <div id="diff-results" style="display: none;">
                    <!-- 统计信息 -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                            <i data-feather="bar-chart-2" class="w-5 h-5 mr-2"></i>
                            对比统计
                        </h3>
                        
                        <div class="grid grid-cols-2 md:grid-cols-5 gap-4 text-center">
                            <div class="bg-green-50 rounded-lg p-3">
                                <div class="text-2xl font-bold text-green-600" id="stat-insertions">0</div>
                                <div class="text-sm text-gray-600">新增</div>
                            </div>
                            <div class="bg-red-50 rounded-lg p-3">
                                <div class="text-2xl font-bold text-red-600" id="stat-deletions">0</div>
                                <div class="text-sm text-gray-600">删除</div>
                            </div>
                            <div class="bg-yellow-50 rounded-lg p-3">
                                <div class="text-2xl font-bold text-yellow-600" id="stat-modifications">0</div>
                                <div class="text-sm text-gray-600">修改</div>
                            </div>
                            <div class="bg-gray-50 rounded-lg p-3">
                                <div class="text-2xl font-bold text-gray-600" id="stat-unchanged">0</div>
                                <div class="text-sm text-gray-600">未变更</div>
                            </div>
                            <div class="bg-blue-50 rounded-lg p-3">
                                <div class="text-2xl font-bold text-blue-600" id="stat-similarity">0%</div>
                                <div class="text-sm text-gray-600">相似度</div>
                            </div>
                        </div>
                    </div>

                    <!-- 对比结果视图 -->
                    <div class="bg-white rounded-lg shadow-lg border border-gray-200 mb-6 overflow-hidden">
                        <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200 p-6">
                            <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center space-y-4 lg:space-y-0">
                                <h3 class="text-xl font-semibold text-gray-800 flex items-center">
                                    <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                                        <i data-feather="git-compare" class="w-6 h-6 text-blue-600"></i>
                                    </div>
                                    对比结果
                                </h3>
                                <div class="flex flex-wrap gap-3">
                                    <button id="export-html" class="bg-purple-600 hover:bg-purple-700 text-white text-sm px-4 py-2.5 rounded-lg flex items-center transition-all duration-200 hover:shadow-lg">
                                        <i data-feather="download" class="w-4 h-4 mr-2"></i>
                                        导出HTML
                                    </button>
                                    <button id="export-patch" class="bg-orange-600 hover:bg-orange-700 text-white text-sm px-4 py-2.5 rounded-lg flex items-center transition-all duration-200 hover:shadow-lg">
                                        <i data-feather="file-text" class="w-4 h-4 mr-2"></i>
                                        导出Patch
                                    </button>
                                    <button id="copy-result" class="bg-green-600 hover:bg-green-700 text-white text-sm px-4 py-2.5 rounded-lg flex items-center transition-all duration-200 hover:shadow-lg">
                                        <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                                        复制结果
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 统一差异视图 -->
                        <div class="p-6 bg-gray-50">
                            <div id="diff-content" class="shadow-sm rounded-lg overflow-hidden bg-white">
                                <!-- 差异内容将在这里显示 -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 使用说明 -->
                <div class="bg-gray-50 rounded-lg p-6 mt-8">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">使用说明</h3>
                    <div class="grid md:grid-cols-2 gap-6 text-sm text-gray-600">
                        <div>
                            <h4 class="font-medium text-gray-700 mb-2">功能特点</h4>
                            <ul class="space-y-1">
                                <li>• 支持按行/单词/字符三种对比粒度</li>
                                <li>• 智能忽略空白字符和大小写选项</li>
                                <li>• 可视化的并排对比和统一差异格式</li>
                                <li>• 支持文件上传和多种导出格式</li>
                                <li>• 详细的统计信息和相似度分析</li>
                            </ul>
                        </div>
                        <div>
                            <h4 class="font-medium text-gray-700 mb-2">适用场景</h4>
                            <ul class="space-y-1">
                                <li>• 代码审查和版本对比</li>
                                <li>• 文档修改前后对比</li>
                                <li>• 配置文件变更检查</li>
                                <li>• 翻译内容差异分析</li>
                                <li>• API响应变化检测</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    static init() {
        // 获取DOM元素
        const originalTextarea = document.getElementById('original-text');
        const modifiedTextarea = document.getElementById('modified-text');
        const compareBtn = document.getElementById('compare-btn');
        const diffResults = document.getElementById('diff-results');
        const originalStats = document.getElementById('original-stats');
        const modifiedStats = document.getElementById('modified-stats');
        const originalFilename = document.getElementById('original-filename');
        const modifiedFilename = document.getElementById('modified-filename');

        // 文件上传
        const uploadOriginal = document.getElementById('upload-original');
        const uploadModified = document.getElementById('upload-modified');
        
        // 清空按钮
        const clearOriginal = document.getElementById('clear-original');
        const clearModified = document.getElementById('clear-modified');

        // 导出和复制按钮
        const exportHtml = document.getElementById('export-html');
        const exportPatch = document.getElementById('export-patch');
        const copyResult = document.getElementById('copy-result');

        let currentDiffData = null;

        // 更新文本统计
        const updateStats = DevToolsUtils.debounce(() => {
            const originalText = originalTextarea.value;
            const modifiedText = modifiedTextarea.value;
            
            originalStats.textContent = `字符: ${originalText.length}, 行数: ${originalText.split('\n').length}`;
            modifiedStats.textContent = `字符: ${modifiedText.length}, 行数: ${modifiedText.split('\n').length}`;
        }, 300);

        originalTextarea.addEventListener('input', updateStats);
        modifiedTextarea.addEventListener('input', updateStats);

        // 文件上传处理
        const handleFileUpload = (file, textarea, filenameSpan) => {
            const maxSize = 5 * 1024 * 1024; // 5MB
            
            if (file.size > maxSize) {
                DevToolsUtils.showToast('文件大小不能超过5MB', 'error');
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                textarea.value = e.target.result;
                filenameSpan.textContent = file.name;
                updateStats();
                DevToolsUtils.showToast(`已加载文件: ${file.name}`, 'success');
            };
            reader.onerror = () => {
                DevToolsUtils.showToast('文件读取失败', 'error');
            };
            reader.readAsText(file);
        };

        uploadOriginal.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileUpload(e.target.files[0], originalTextarea, originalFilename);
            }
        });

        uploadModified.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileUpload(e.target.files[0], modifiedTextarea, modifiedFilename);
            }
        });

        // 清空功能
        clearOriginal.addEventListener('click', () => {
            originalTextarea.value = '';
            originalFilename.textContent = '';
            updateStats();
        });

        clearModified.addEventListener('click', () => {
            modifiedTextarea.value = '';
            modifiedFilename.textContent = '';
            updateStats();
        });

        // 拖拽上传
        const setupDragAndDrop = (textarea, filenameSpan) => {
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                textarea.addEventListener(eventName, (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                });
            });

            ['dragenter', 'dragover'].forEach(eventName => {
                textarea.addEventListener(eventName, () => {
                    textarea.classList.add('border-blue-400', 'bg-blue-50');
                });
            });

            ['dragleave', 'drop'].forEach(eventName => {
                textarea.addEventListener(eventName, () => {
                    textarea.classList.remove('border-blue-400', 'bg-blue-50');
                });
            });

            textarea.addEventListener('drop', (e) => {
                const files = Array.from(e.dataTransfer.files);
                if (files.length > 0) {
                    handleFileUpload(files[0], textarea, filenameSpan);
                }
            });
        };

        setupDragAndDrop(originalTextarea, originalFilename);
        setupDragAndDrop(modifiedTextarea, modifiedFilename);

        // 对比功能
        compareBtn.addEventListener('click', () => {
            const originalText = originalTextarea.value;
            const modifiedText = modifiedTextarea.value;

            if (!originalText && !modifiedText) {
                DevToolsUtils.showToast('请输入要对比的文本内容', 'error');
                return;
            }

            DevToolsUtils.addLoading(compareBtn, '对比中...');

            setTimeout(() => {
                try {
                    const options = {
                        ignoreWhitespace: document.getElementById('ignore-whitespace').checked,
                        ignoreCase: document.getElementById('ignore-case').checked,
                        contextLines: parseInt(document.getElementById('context-lines').value) || 3,
                        splitBy: document.getElementById('split-by').value,
                        showLineNumbers: document.getElementById('show-line-numbers').checked
                    };

                    const result = TextDiff.compare(originalText, modifiedText, options);

                    if (result.success) {
                        currentDiffData = result.data;
                        displayDiffResults(result.data);
                        DevToolsUtils.showToast('对比完成！', 'success');
                    } else {
                        DevToolsUtils.showToast(result.error, 'error');
                    }
                } catch (error) {
                    DevToolsUtils.showToast('对比过程中发生错误', 'error');
                    console.error('Text diff error:', error);
                } finally {
                    DevToolsUtils.removeLoading(compareBtn, '开始对比');
                }
            }, 100);
        });

        // 显示对比结果
        const displayDiffResults = (data) => {
            // 显示统计信息
            document.getElementById('stat-insertions').textContent = data.stats.insertions;
            document.getElementById('stat-deletions').textContent = data.stats.deletions;
            document.getElementById('stat-modifications').textContent = data.stats.modifications;
            document.getElementById('stat-unchanged').textContent = data.stats.unchanged;
            document.getElementById('stat-similarity').textContent = data.stats.similarity + '%';

            // 显示统一差异HTML视图
            const diffContentEl = document.getElementById('diff-content');
            if (data.unifiedHtml) {
                diffContentEl.innerHTML = `<div class="max-h-[500px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">${data.unifiedHtml}</div>`;
            } else {
                diffContentEl.innerHTML = `<div class="p-12 text-center text-gray-500 bg-gradient-to-br from-gray-50 to-white rounded-lg border-2 border-dashed border-gray-200">
                    <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i data-feather="check-circle" class="w-8 h-8 text-green-600"></i>
                    </div>
                    <p class="text-xl font-semibold text-gray-700 mb-2">完全匹配</p>
                    <p class="text-sm text-gray-500">两段文本内容完全相同，没有发现任何差异</p>
                </div>`;
            }

            // 显示结果区域
            diffResults.style.display = 'block';
            diffResults.scrollIntoView({ behavior: 'smooth' });
            
            // 初始化图标
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 100);
        };


        // 导出功能
        exportHtml.addEventListener('click', () => {
            if (!currentDiffData) {
                DevToolsUtils.showToast('请先进行文本对比', 'error');
                return;
            }

            const result = TextDiff.exportDiff(currentDiffData, 'html');
            if (result.success) {
                const blob = new Blob([result.data.content], { type: result.data.mimeType });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = result.data.filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                DevToolsUtils.showToast('HTML文件下载已开始', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        });

        exportPatch.addEventListener('click', () => {
            if (!currentDiffData) {
                DevToolsUtils.showToast('请先进行文本对比', 'error');
                return;
            }

            const result = TextDiff.exportDiff(currentDiffData, 'unified');
            if (result.success) {
                const blob = new Blob([result.data.content], { type: result.data.mimeType });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = result.data.filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                DevToolsUtils.showToast('Patch文件下载已开始', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        });

        // 复制功能
        copyResult.addEventListener('click', async () => {
            if (!currentDiffData) {
                DevToolsUtils.showToast('请先进行文本对比', 'error');
                return;
            }

            const success = await DevToolsUtils.copyToClipboard(currentDiffData.unifiedDiff || '没有差异');
            if (success) {
                DevToolsUtils.showToast('已复制到剪贴板', 'success');
            }
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                compareBtn.click();
            }
        });

        // 初始化统计
        updateStats();

        // 初始化图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};